//gcc -o callerid *.c -lpulse-simple -lpulse

#include <stdio.h>
#include <string.h>
#include "alaw.h"
#include "ulaw.h"
#include "callerid.h"
#include <errno.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <unistd.h>
#include <fcntl.h>

int make_named_socket (const char *filename)
{
	struct sockaddr_un remote;
	int s;
	int len;
	int etat;
	
	/* Create the socket.   */
	
	s = socket (AF_UNIX, SOCK_STREAM, 0);
	if (s < 0)
    {
		printf("sock create error");
		perror ("socket");
		exit (EXIT_FAILURE);
    }
	
	/* Bind a name to the socket.   */
	
	remote.sun_family = AF_UNIX;
	strcpy (remote.sun_path, filename);
	
	/* The size of the address is
     the offset of the start of the filename,
     plus its length,
     plus one for the terminating null byte.  */
	len = strlen(remote.sun_path) + sizeof(remote.sun_family);
	
	if (connect (s, (struct sockaddr *) &remote, len) < 0)
    {
		printf("sock address bind error");
		perror ("bind");
		exit (EXIT_FAILURE);
    }
	
	etat = O_NONBLOCK;
	fcntl(s,F_SETFL,etat);
	printf("Connected.\n");
	
	return s;
}

int main(int argc,char *argv[])
{
	int s, t, len;
	int etat,pid;
	struct sockaddr_un remote;
	char str[100];
	
	if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
		perror("socket");
		exit(1);
	}
	
	if ( argc < 2 ){
		printf("usage: %s socketFile\n" , argv[0] );
		exit(4);
	}
	
	printf("Trying to connect...\n");
	
	remote.sun_family = AF_UNIX;
	strcpy(remote.sun_path, argv[1]);
	len = strlen(remote.sun_path) + sizeof(remote.sun_family);
	if (connect(s, (struct sockaddr *)&remote, len) == -1) {
		perror("connect");
		exit(1);
	}
	//etat=fcntl(s,F_GETFL);
	etat = O_NONBLOCK;
	fcntl(s,F_SETFL,etat);
	printf("Connected.\n");
	if ((pid=fork())<0) {
		printf("erreur fork\n");
		return (-1);
	}
	if (pid==0){
		while(printf("SEND> "), fgets(str, 100, stdin), !feof(stdin)) {
			if (strcmp(str, "SENDCID\n") == 0){
				printf("Sending Off-hook CID\n");
				//write(s, "CIDAUDIO ON\n", 12);
				send_cid("4018220534", "Andrew Nagel", 0, 1);
				//write(s, "CIDAUDIO OFF\n", 13);
			} else if (write(s, str,strlen(str)) == -1) {
                perror("send");
                exit(1);
            }
        }
	}else{
		while(1){
			if ((t=read(s, str,100)) >= 0) {
				str[t] = '\0';
				if (t>0) 
				{	
					printf("RECV> %s", str);
					if (strcmp(str, "SENDCID\n") == 0)
					{
						printf("Need to send CID\n");
						write(s, "CIDAUDIO ON\n", 12);
						send_cid("4018220534", "Andrew Nagel", 0, 0);
						write(s, "CIDAUDIO OFF\n", 13);
					}
					
				}
			}
		}
	}
	close(s);
	
	return 0;
}
